layui.define(['form', 'zadmin', 'layer', 'table'], function(exports) {
    var form = layui.form,
        $ = layui.jquery,
        zadmin = layui.zadmin,
        layer = layui.layer,
        table = layui.table,
        groups;
    $.post(window.location.href, { want: 'init' }, function(res) {
        zadmin.showReturn(res, function(res) {
            groups = res.data.groups;
            var cols = [
                [
                    { checkbox: true, rowspan: 2, fixed: 'left' },
                    { field: 'user_id', title: 'ID', width: 60, fixed: 'left', rowspan: 2, align: 'center', sort: true },
                    { field: 'email', title: '邮箱', width: 150, rowspan: 2, align: 'center' },
                    { title: '操作', fixed: '', rowspan: 2, align: 'center', templet: '#itemBar', width: 115 },
                    {
                        field: 'group_id',
                        title: '用户组',
                        width: 100,
                        rowspan: 2,
                        align: 'center',
                        templet: function(obj) {
                            return groups[obj.group_id];
                        }
                    },
                    {
                        field: 'status',
                        title: '状态',
                        width: 60,
                        rowspan: 2,
                        align: 'center',
                        templet: function(obj) {
                            return obj.status == 1 ? '正常' : '<span class="z-red">禁用</span>';
                        }
                    },
                    {
                        field: 'addition',
                        title: '备注',
                        edit: true,
                        width: 80,
                        rowspan: 2,
                        align: 'center',
                    },
                    { field: 'create_time', title: '注册时间', width: 160, rowspan: 2, align: 'center', sort: true },
                    { field: 'create_ip', title: '注册IP', width: 100, rowspan: 2, align: 'center' },
                    { field: 'login_time', title: '登录时间', width: 160, rowspan: 2, align: 'center', sort: true },
                    { field: 'login_ip', title: '登录IP', width: 100, rowspan: 2, align: 'center' },
                    {
                        field: 'avatar',
                        title: '头像',
                        width: 60,
                        rowspan: 2,
                        align: 'center',
                        templet: function(obj) {
                            var avatar = obj.avatar && obj.avatar.length > 0 ? '/storage/' + obj.avatar : '/static/img/avatar.png';
                            return '<img src="' + avatar + '" onerror="this.src=\'/static/img/avatar.png\'" height="20"/>';
                        }
                    },
                ],
                []
            ];
            for (var i = 0; i < res.data.infomods.length; i++) {
                cols[0].push({ title: res.data.infomods[i], colspan: res.data.modFields[i].length, align: 'center' });
                for (var j = 0; j < res.data.modFields[i].length; j++) {
                    var item = res.data.modFields[i][j];
                    var newObj = {
                        title: item.title,
                        field: item.field,
                        align: 'center',
                        width: 100,
                        fieldType: item.type,
                        setting: item.setting,
                    }
                    if (['switch', 'radio', 'checkbox', 'select'].indexOf(item.type) >= 0) {
                        newObj.templet = function(obj) {
                            var val = obj[this.field]; //当前项的值
                            if (val.length == 0) return '';
                            if (this.fieldType == 'switch') {
                                var setting = this.setting.split(',');
                                if (typeof setting[val] != 'undefined' && setting[val] != null && setting[val].length > 0) {
                                    return setting[val];
                                } else {
                                    if (val == 0) {
                                        return '否';
                                    } else {
                                        return '是';
                                    }
                                }
                            } else {
                                var values = {};
                                this.setting.split(',').forEach(function(n) {
                                    var v = n.split('|');
                                    if (v.length >= 2 && v[1].length > 0) {
                                        values[v[0]] = v[1];
                                    } else {
                                        values[v[0]] = v[0];
                                    }
                                })
                                if (this.fieldType == 'radio' || this.fieldType == 'select') {
                                    return values[val];
                                } else {
                                    val = val.split(',');
                                    val = val.map(function(n) {
                                        return values[n];
                                    })
                                    return val.join(',');
                                }
                            }
                        }
                    }

                    cols[1].push(newObj)
                }
            }
            var tableIns = table.render({
                toolbar: '#toolbarDemo',
                elem: '#test',
                url: window.location.href,
                title: '用户列表',
                where: {
                    field: 'user_id',
                    type: 'desc'
                },
                initSort: {
                    field: 'user_id',
                    type: 'desc'
                },
                cols: cols,
                page: true,
                autoSort: false,
                response: {
                    statusCode: 200
                }
            });
            table.on('sort(test)', function(obj) {
                tableIns.reload({
                    initSort: obj,
                    where: {
                        field: obj.field,
                        order: obj.type
                    }
                });
            });
            table.on('edit(test)', function(obj) {
                var loadingIndex = zadmin.loading();
                $.post(window.location.href, { want: 'field', field: obj.field, value: obj.value, user_id: obj.data.user_id }, function(res) {
                    layer.close(loadingIndex);
                    zadmin.showReturn(res, function(res) {
                        layer.close(index);
                    });
                })
            });
            table.on('tool(test)', function(obj) {
                var data = obj.data;
                if (obj.event === 'password') {
                    var code = '<form class="layui-form" method="post" lay-filter="layerform">';
                    code += zadmin.form.row('新密码', 'password', 'text');
                    code += '</form>';
                    layer.open({
                        title: '修改密码（用户ID：' + data.user_id + '）',
                        content: code,
                        success: function() {
                            form.render();
                        },
                        yes: function(index) {
                            var vals = form.val('layerform');
                            var loadingIndex = zadmin.loading();
                            vals.want = obj.event;
                            vals.user_id = data.user_id;
                            $.post(window.location.href, vals, function(res) {
                                layer.close(loadingIndex);
                                zadmin.showReturn(res, function(res) {
                                    layer.close(index);
                                    tableIns.reload();
                                });
                            })
                        }
                    })
                } else if (obj.event === 'login') {
                    layer.confirm('您即将登录' + data.email, {
                        title: '操作提示',
                    }, function(index, layero) {
                        var loadingIndex = zadmin.loading();
                        $.post(window.location.href, {want:'login',user_id:data.user_id}, function(res) {
                            layer.close(loadingIndex);
                            zadmin.showReturn(res);
                        })
                    })
                } else if (obj.event === 'delete') {
                    var code = '您确认要删除' + obj.data.email + '吗？';
                    layer.open({
                        title: '操作提示',
                        content: code,
                        yes: function(index) {
                            var loadingIndex = zadmin.loading();
                            var vals = {
                                want: 'multiDelete',
                                users: [data.user_id]
                            };
                            $.post(window.location.href, vals, function(res) {
                                layer.close(loadingIndex);
                                zadmin.showReturn(res, function(res) {
                                    layer.close(index);
                                    tableIns.reload();
                                });
                            })
                        }
                    })
                }
            });

            table.on('toolbar(test)', function(obj) {
                if (obj.event === 'add') {
                    var code = '<form class="layui-form" method="post" lay-filter="layerform">';
                    code += zadmin.form.row('邮箱', 'email', 'text', '', true);
                    code += zadmin.form.row('密码', 'password', 'text', '', true);
                    code += zadmin.form.row('用户组', 'group_id', 'select', '', true, groups);
                    code += zadmin.form.row('状态', 'status', 'select', '1', true, { '1': '正常', '0': '禁用' });
                    code += zadmin.form.row('备注', 'addition', 'text');
                    code += '</form>';
                    layer.open({
                        title: '添加用户',
                        content: code,
                        success: function() {
                            form.render();
                        },
                        yes: function(index) {
                            var vals = form.val('layerform');
                            var loadingIndex = zadmin.loading();
                            vals.want = 'add';
                            $.post(window.location.href, vals, function(res) {
                                layer.close(loadingIndex);
                                zadmin.showReturn(res, function(res) {
                                    layer.close(index);
                                    tableIns.reload();
                                });
                            })
                        }
                    })
                } else if (obj.event === 'multiGroup') {
                    if (table.checkStatus('test').data.length == 0) {
                        return layer.msg('请先选择要修改的用户');
                    }
                    var code = '<form class="layui-form" method="post" lay-filter="layerform">';
                    code += zadmin.form.row('用户组', 'group_id', 'select', '', true, groups);
                    code += '</form>';
                    layer.open({
                        title: '批量修改用户组',
                        content: code,
                        area:['400px',"300px"],
                        success: function() {
                            form.render();
                        },
                        yes: function(index) {
                            var vals = form.val('layerform');
                            var loadingIndex = zadmin.loading();
                            vals.want = obj.event;
                            vals.users = table.checkStatus('test').data.map(function(n) {
                                return n.user_id;
                            })
                            $.post(window.location.href, vals, function(res) {
                                layer.close(loadingIndex);
                                zadmin.showReturn(res, function(res) {
                                    layer.close(index);
                                    tableIns.reload();
                                });
                            })
                        }
                    })
                } else if (obj.event === 'multiStatus') {
                    if (table.checkStatus('test').data.length == 0) {
                        return layer.msg('请先选择要修改的用户');
                    }
                    var code = '<form class="layui-form" method="post" lay-filter="layerform">';
                    code += zadmin.form.row('状态', 'status', 'select', 1, true, { 1: '正常', 0: '禁用' });
                    code += '</form>';
                    layer.open({
                        title: '批量修改状态',
                        content: code,
                        success: function() {
                            form.render();
                        },
                        yes: function(index) {
                            var vals = form.val('layerform');
                            var loadingIndex = zadmin.loading();
                            vals.want = obj.event;
                            vals.users = table.checkStatus('test').data.map(function(n) {
                                return n.user_id;
                            })
                            $.post(window.location.href, vals, function(res) {
                                layer.close(loadingIndex);
                                zadmin.showReturn(res, function(res) {
                                    layer.close(index);
                                    tableIns.reload();
                                });
                            })
                        }
                    })
                } else if (obj.event === 'multiDelete') {
                    if (table.checkStatus('test').data.length == 0) {
                        return layer.msg('请先选择要删除的用户');
                    }
                    var users = table.checkStatus('test').data.map(function(n) {
                        return n.email;
                    });
                    var code = '您确认要删除' + users.join(',') + '共' + users.length + '个用户吗？';
                    layer.open({
                        title: '批量删除',
                        content: code,
                        yes: function(index) {
                            var val = {};
                            var loadingIndex = zadmin.loading();
                            vals.want = obj.event;
                            vals.users = table.checkStatus('test').data.map(function(n) {
                                return n.user_id;
                            })
                            $.post(window.location.href, vals, function(res) {
                                layer.close(loadingIndex);
                                zadmin.showReturn(res, function(res) {
                                    layer.close(index);
                                    tableIns.reload();
                                });
                            })
                        }
                    })
                }
            });
        })

    })

    exports('list', {})
})